package com.zdkj.subway.stm.util;

import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import lombok.experimental.UtilityClass;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

/**
 * @support:
 * @author: chen
 * @version: 1.0
 * @Date: 2020-01-13 15:17:37.
 * @Description: <p>
 *
 * 车站票款差异个性化  set默认值  加入 线路 站点code
 * </p>
 */
@UtilityClass
public class ObjectValueUtils {

    //Object转BigDecimal
    public static BigDecimal getBigDecimal( Object value ) {
        BigDecimal val = null;
        if( value != null ) {
            if( value instanceof BigDecimal ) {
                val = (BigDecimal) value;
            } else if( value instanceof String ) {
                val = new BigDecimal( (String) value );
            } else if( value instanceof BigInteger) {
                val = new BigDecimal( (BigInteger) value );
            } else if( value instanceof Number ) {
                val = new BigDecimal( ((Number)value).doubleValue() );
            } else {
                throw new ClassCastException("Not possible to coerce ["+value+"] from class "+value.getClass()+" into a BigDecimal.");
            }
        }
        return val;
    }

    public <T> T getDefaultObj(Class<T> cls) {
        T obj = null;
        try {
            obj = cls.newInstance();
            setDefaultFiledValue(obj);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public void setDefaultFiledValue(Object obj) {
        Class clz = obj.getClass();
        PigxUser user = SecurityUtils.getUser();
        Map<String, Object> filedMap = new HashMap<String, Object>(5) {{
            if (null != user) {
                put("creatorId", user.getId());
                put("creatorName", user.getNikeName());
                put("deptId", user.getDeptId());
                put("lineCode", user.getLineCode());
                put("stationCode", user.getStationCode());
            }

        }};

        for (String filedName : filedMap.keySet()) {
            Field field;
            try {
                field = clz.getDeclaredField(filedName);
                field.setAccessible(true);
                field.set(obj, filedMap.get(filedName));
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } finally {
                continue;
            }
        }
    }
}
